package com.yuexin.project.order.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.aspectj.lang.annotation.Log;
import com.yuexin.framework.aspectj.lang.enums.BusinessType;
import com.yuexin.framework.web.controller.BaseController;
import com.yuexin.framework.web.domain.AjaxResult;
import com.yuexin.framework.web.page.TableDataInfo;
import com.yuexin.project.order.domain.MealsSetting;
import com.yuexin.project.order.service.ISettingService;
import com.yuexin.project.system.user.domain.User;
import com.yuexin.project.system.user.mapper.UserMapper;

/**
 * 报餐设置 信息操作处理
 *
 * @author yuexin
 * @date 2018-10-22
 */
@Controller
@RequestMapping("/order/setting")
public class SettingController extends BaseController {
    private String prefix = "order/setting";

    @Autowired
    private ISettingService settingService;

    @Autowired
    private UserMapper userMapper;

    public List<User> selectGuestsByUserId(Integer mealsId, String companyId) {
        List<User> userPosts = userMapper.selectUsersByGuestId(mealsId);
        List<User> posts = userMapper.selectUserAllByCompanyId(companyId);
        for (User post : posts) {
            for (User userRole : userPosts) {
                if (post.getUserId().longValue() == userRole.getUserId().longValue()) {
                    post.setFlag(true);
                    break;
                }
            }
        }
        return posts;
    }

    public List<User> selectPerisByUserId(Integer mealsId, String companyId) {
        List<User> userPosts = userMapper.selectUsersByperiId(mealsId);
        List<User> posts = userMapper.selectUserAllByCompanyId(companyId);
        for (User post : posts) {
            for (User userRole : userPosts) {
                if (post.getUserId().longValue() == userRole.getUserId().longValue()) {
                    post.setFlag(true);
                    break;
                }
            }
        }
        return posts;
    }

    public List<User> selectManagerByUserId(Integer mealsId, String companyId) {
        List<User> userPosts = userMapper.selectUsersByManagerId(mealsId);
        List<User> posts = userMapper.selectUserAllByCompanyId(companyId);
        for (User post : posts) {
            for (User userRole : userPosts) {
                if (post.getUserId().longValue() == userRole.getUserId().longValue()) {
                    post.setFlag(true);
                    break;
                }
            }
        }
        return posts;
    }

    public List<User> selectCookUserByUserId(Integer mealsId, String companyId) {
        List<User> userPosts = userMapper.selectCookUsersByMealsId(mealsId);
        List<User> posts = userMapper.selectUserAllByCompanyId(companyId);
        for (User post : posts) {
            for (User userRole : userPosts) {
                if (post.getUserId().longValue() == userRole.getUserId().longValue()) {
                    post.setFlag(true);
                    break;
                }
            }
        }
        return posts;
    }

    private boolean isExistCompanySetting() {
        boolean result = false;
        MealsSetting mealsSetting = settingService.selectSettingByCompanyId(ShiroUtils.getCompanyId());
        if (mealsSetting != null) {
            result = true;
        }
        return result;
    }

    @RequiresPermissions("order:setting:view")
    @GetMapping()
    public String setting(ModelMap mmap) {
        String companyId = ShiroUtils.getCompanyId();
        MealsSetting setting = null;
        if (isExistCompanySetting()) {
            setting = settingService.selectSettingByCompanyId(companyId);
        } else {
            setting = settingService.selectSettingByCompanyId("dingcan");
        }
        if("1".equals(setting.getBreakfastType())){
            setting.setBreakfastType2(setting.getBreakfastType1());
            setting.setBreakfastType1(null);
        }
        if("1".equals(setting.getLunchType())){
            setting.setLunchType2(setting.getLunchType1());
            setting.setLunchType1(null);
        }
        if("1".equals(setting.getDinnerType())){
            setting.setDinnerType2(setting.getDinnerType1());
            setting.setDinnerType1(null);
        }
        if("1".equals(setting.getOtherType())){
            setting.setOtherType2(setting.getOtherType1());
            setting.setOtherType1(null);
        }
        mmap.put("settings", setting);
        Integer mealsId = setting.getMealsId();
        mmap.put("guestUsers", selectGuestsByUserId(mealsId, companyId));
        mmap.put("periUsers", selectPerisByUserId(mealsId, companyId));
        mmap.put("mealsUsers", selectManagerByUserId(mealsId, companyId));
        mmap.put("cookUsers", selectCookUserByUserId(mealsId, companyId));
        return prefix + "/setting";
    }

    /**
     * 查询报餐设置列表
     */
    @RequiresPermissions("order:setting:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MealsSetting mealsSetting) {
        startPage();
        List<MealsSetting> list = settingService.selectSettingList(mealsSetting);
        return getDataTable(list);
    }

    /**
     * 新增报餐设置
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存报餐设置
     */
    @RequiresPermissions("order:setting:add")
    @Log(title = "报餐设置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MealsSetting mealsSetting) {
        return toAjax(settingService.insertSetting(mealsSetting));
    }

    /**
     * 修改报餐设置
     */
    @GetMapping("/edit/{mealsId}")
    public String edit(@PathVariable("mealsId") Integer mealsId, ModelMap mmap) {
        MealsSetting mealsSetting = settingService.selectSettingByCompanyId(ShiroUtils.getCompanyId());
        mmap.put("setting", mealsSetting);
        //mmap.put("users", userMapper.selectUsersByGuestId(1));
        return prefix + "/edit";
    }

    private boolean compareTime(String start, String end) {
        boolean result = false;
        DateFormat df = new SimpleDateFormat("HH:mm");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd
        try {
            Date startDate = df.parse(start);//将字符串转换为date类型
            Date endDate = df.parse(end);
            if (startDate.getTime() <= endDate.getTime())//比较时间大小
            {
                result = true;
            }
        } catch (ParseException e) {
            result = false;
        }
        return result;
    }

    /**
     * 修改保存报餐设置
     */
    @RequiresPermissions("order:setting:edit")
    @Log(title = "报餐设置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MealsSetting mealsSetting) {
        String breakfastStart = mealsSetting.getBreakfastStart();
        String breakfastEnd = mealsSetting.getBreakfastEnd();
        String lunchStart = mealsSetting.getLunchStart();
        String lunchEnd = mealsSetting.getLunchEnd();
        String dinnerStart = mealsSetting.getDinnerStart();
        String dinnerEnd = mealsSetting.getDinnerEnd();
        String otherStart = mealsSetting.getOtherStart();
        String otherEnd = mealsSetting.getOtherEnd();
//        if("1".equals(mealsSetting.getBreakfastType())){
//            mealsSetting.setBreakfastType1(mealsSetting.getBreakfastType2());
//        }
//        if("1".equals(mealsSetting.getLunchType())){
//            mealsSetting.setLunchType1(mealsSetting.getLunchType2());
//        }
//        if("1".equals(mealsSetting.getDinnerType())){
//            mealsSetting.setDinnerType1(mealsSetting.getDinnerType2());
//        }
//        if("1".equals(mealsSetting.getOtherType())){
//            mealsSetting.setOtherType1(mealsSetting.getOtherType2());
//        }
        //结束时间不能小于开始时间
        if (!compareTime(breakfastStart, breakfastEnd) || !compareTime(lunchStart, lunchEnd) || !compareTime(dinnerStart, dinnerEnd) || !compareTime(otherStart, otherEnd)) {
            return error("就餐结束时间不可小于开始时间！");
        }

        //餐别时间不能重叠
//        if (!compareTime(breakfastEnd, lunchStart) || !compareTime(lunchEnd, dinnerStart) || !compareTime(dinnerStart, otherStart)) {
//            return error("就餐时间不可重叠！");
//        }
        mealsSetting.setCompanyId(ShiroUtils.getCompanyId());
        if (isExistCompanySetting()) {
            return toAjax(settingService.updateSetting(0, mealsSetting));
        } else {
            mealsSetting.setMealsId(null);
            return toAjax(settingService.insertSetting(mealsSetting));
        }
    }

    /**
     * 删除报餐设置
     */
    @RequiresPermissions("order:setting:remove")
    @Log(title = "报餐设置", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(settingService.deleteSettingByIds(ids));
    }

    /**
     * 恢复保存报餐设置
     */
    @RequiresPermissions("order:setting:recovery")
    @Log(title = "报餐设置", businessType = BusinessType.UPDATE)
    @PostMapping("/recovery")
    @ResponseBody
    public AjaxResult recovery(MealsSetting mealsSetting) {
        mealsSetting.setCompanyId(ShiroUtils.getCompanyId());
        return toAjax(settingService.updateSetting(1, mealsSetting));
    }

}
